package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.util.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author: Bright
 * @Date: 2022-04-15 19:12
 * @Description: com.atguigu.srb.oss.service.impl
 * @version: 1.0
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String model, String fileName) {

        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(OssProperties.BUCKET_NAME);
            ossClient.createBucket(createBucketRequest);
        }
        String dateFoler = new DateTime().toString("/yyyy/MM/dd");

        fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        String key = model + dateFoler + fileName;
        PutObjectResult putObjectResult = ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);
        System.out.println(putObjectResult);
        //关闭OSSClient。
        ossClient.shutdown();

        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;
    }

    @Override
    public void removeFile(String url) {

        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
        String filename = url.substring(host.length());
        ossClient.deleteObject(OssProperties.BUCKET_NAME, filename);
        ossClient.shutdown();

    }
}
